All files / app/api/posts/[id] route.ts

0% Statements 0/72
0% Branches 0/48
0% Functions 0/3
0% Lines 0/65

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208                                                                                                                                                                                                                                                                                                                                                                                                                               
import { NextRequest, NextResponse } from "next/server";
import { connectDB } from "@/lib/mongodb";
import { requireAuth } from "@/lib/session";
import Post from "@/models/Post";
import AuditLog from "@/models/AuditLog";
 
type Params = Promise<{ id: string }>;
 
// GET /api/posts/[id] - Get a single post
export async function GET(
  request: NextRequest,
  { params }: { params: Params }
) {
  try {
    const session = await requireAuth();
    await connectDB();
 
    const { id } = await params;
 
    const post = await Post.findById(id)
      .select("-__v")
      .populate("authorId", "name email image")
      .populate("categoryId", "name slug description");
 
    if (!post || post.deletedAt) {
      return NextResponse.json(
        { error: { code: "NOT_FOUND", message: "Post not found" } },
        { status: 404 }
      );
    }
 
    // Check visibility permissions
    if (
      post.visibility === "private" &&
      post.authorId._id.toString() !== session.user.id
    ) {
      return NextResponse.json(
        { error: { code: "FORBIDDEN", message: "Access denied" } },
        { status: 403 }
      );
    }
 
    return NextResponse.json({ data: post });
  } catch (error) {
    if (error instanceof Error && error.message === "Unauthorized") {
      return NextResponse.json(
        { error: { code: "UNAUTHORIZED", message: "Authentication required" } },
        { status: 401 }
      );
    }
    console.error("Error fetching post:", error);
    return NextResponse.json(
      {
        error: {
          code: "INTERNAL_ERROR",
          message: "Failed to fetch post",
        },
      },
      { status: 500 }
    );
  }
}
 
// PATCH /api/posts/[id] - Update a post
export async function PATCH(
  request: NextRequest,
  { params }: { params: Params }
) {
  try {
    const session = await requireAuth();
    await connectDB();
 
    const { id } = await params;
    const body = await request.json();
 
    const post = await Post.findById(id);
 
    if (!post || post.deletedAt) {
      return NextResponse.json(
        { error: { code: "NOT_FOUND", message: "Post not found" } },
        { status: 404 }
      );
    }
 
    // Check ownership
    if (post.authorId.toString() !== session.user.id) {
      return NextResponse.json(
        { error: { code: "FORBIDDEN", message: "You can only edit your own posts" } },
        { status: 403 }
      );
    }
 
    // Update allowed fields
    if (body.title !== undefined) post.title = body.title;
    if (body.summary !== undefined) post.summary = body.summary;
    if (body.body !== undefined) post.body = body.body;
    if (body.tags !== undefined) post.tags = body.tags;
    if (body.visibility !== undefined) post.visibility = body.visibility;
    if (body.allowComments !== undefined) post.allowComments = body.allowComments;
    if (body.categoryId !== undefined) post.categoryId = body.categoryId;
 
    await post.save();
 
    // Create audit log
    await AuditLog.create({
      entityType: "post",
      entityId: post._id,
      action: "updated",
      userId: session.user.id,
      payload: body,
    });
 
    const updatedPost = await Post.findById(post._id)
      .select("-__v")
      .populate("authorId", "name email image")
      .populate("categoryId", "name slug description");
 
    return NextResponse.json({ data: updatedPost });
  } catch (error) {
    if (error instanceof Error && error.message === "Unauthorized") {
      return NextResponse.json(
        { error: { code: "UNAUTHORIZED", message: "Authentication required" } },
        { status: 401 }
      );
    }
    console.error("Error updating post:", error);
    return NextResponse.json(
      {
        error: {
          code: "INTERNAL_ERROR",
          message: "Failed to update post",
        },
      },
      { status: 500 }
    );
  }
}
 
// DELETE /api/posts/[id] - Delete a post (soft delete)
export async function DELETE(
  request: NextRequest,
  { params }: { params: Params }
) {
  try {
    const session = await requireAuth();
    await connectDB();
 
    const { id } = await params;
 
    const post = await Post.findById(id);
 
    if (!post || post.deletedAt) {
      return NextResponse.json(
        { error: { code: "NOT_FOUND", message: "Post not found" } },
        { status: 404 }
      );
    }
 
    // Check ownership or admin
    if (
      post.authorId.toString() !== session.user.id &&
      session.user.role !== "admin"
    ) {
      return NextResponse.json(
        {
          error: {
            code: "FORBIDDEN",
            message: "You can only delete your own posts",
          },
        },
        { status: 403 }
      );
    }
 
    // Soft delete
    post.deletedAt = new Date();
    post.visibility = "private";
    await post.save();
 
    // Create audit log
    await AuditLog.create({
      entityType: "post",
      entityId: post._id,
      action: "deleted",
      userId: session.user.id,
    });
 
    return new NextResponse(null, { status: 204 });
  } catch (error) {
    if (error instanceof Error && error.message === "Unauthorized") {
      return NextResponse.json(
        { error: { code: "UNAUTHORIZED", message: "Authentication required" } },
        { status: 401 }
      );
    }
    console.error("Error deleting post:", error);
    return NextResponse.json(
      {
        error: {
          code: "INTERNAL_ERROR",
          message: "Failed to delete post",
        },
      },
      { status: 500 }
    );
  }
}